<?php

namespace app\repository;

use app\popo\model\Setmeal;
use app\popo\model\SetmealDish;
use app\support\JwtHelper;
use app\support\ListContainer;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;

class SetmealRepository
{
    public function listOf(array $setmealPageQueryDTO)
    {
        $categoryId = Arr::get($setmealPageQueryDTO, "categoryId");
        $name = Arr::get($setmealPageQueryDTO, "name");
        $status = Arr::get($setmealPageQueryDTO, "status");
        $pageSize = Arr::get($setmealPageQueryDTO, "pageSize");

        $query = Setmeal::query()
            ->when($categoryId, function (Builder $builder) use ($categoryId) {
                $builder->where("category_id", $categoryId);

            })
            ->when($name, function (Builder $builder) use ($name) {
                $name = "%$name%";
                $builder->where("name", "like", $name);

            })
            ->when($status, function (Builder $builder) use ($status) {
                $builder->where("status", $status);
            })->orderByDesc("update_time");

        return new ListContainer($query->paginate($pageSize), function (Setmeal $setmeal) {
            $item = $setmeal->toArray();
            $item["categoryId"] = (string)$item["category_id"];
            $item["updateTime"] = $item["update_time"] ? Carbon::parse($item["update_time"])->format("Y-m-d H:i:s") : null;

            return $item;
        });
    }

    public function saveWithDishes(array $data)
    {
        // 保存套餐
        $setmeal = new Setmeal();
        $setmeal->category_id = $data['categoryId'];
        $setmeal->description = $data['description'];
        $setmeal->image = $data['image'];
        $setmeal->name = $data['name'];
        $setmeal->price = $data['price'];
        $setmeal->status = $data['status'];
        $setmeal->create_user = JwtHelper::getEmployee()->id;
        $setmeal->save();

        // 批量保存套餐菜品
        if (!empty($data['setmealDishes']) && is_array($data['setmealDishes'])) {
            $insertData = [];
            foreach ($data['setmealDishes'] as $dishData) {
                $insertData[] = [
                    'setmeal_id' => $setmeal->id,
                    'dish_id' => $dishData['dishId'],
                    'name' => $dishData['name'],
                    'price' => $dishData['price'],
                    'copies' => $dishData['copies'],
                ];
            }

            if ($insertData) {
                SetmealDish::insert($insertData);
            }
        }

    }

    public function getById($id)
    {
        // 1. 查询套餐及关联分类
        $setmeal = Setmeal::with('category')
            ->find($id);


        if (!$setmeal) {
            return array();
        }

        // 2. 查询套餐关联的菜品
        $setmealDishes = SetmealDish::where('setmeal_id', $setmeal->id)
            ->get()
            ->map(function ($dish) {
                return [
                    'id' => (string)$dish->id,
                    'dishId' => (string)$dish->dish_id,
                    'setmealId' => (string)$dish->setmeal_id,
                    'name' => $dish->name,
                    'price' => $dish->price,
                    'copies' => $dish->copies,
                ];
            });

        // 3. 组装最终返回结构
        return [
            'id' => (string)$setmeal->id,
            'name' => $setmeal->name,
            'price' => $setmeal->price,
            'description' => $setmeal->description,
            'image' => $setmeal->image,
            'status' => $setmeal->status,
            'categoryId' => (string)$setmeal->category_id,
            'categoryName' => $setmeal->category->name ?? '',
            'updateTime' => optional($setmeal->updated_at)->toISOString(), // Carbon 对象转 ISO8601
            'setmealDishes' => $setmealDishes,
        ];
    }

    public function startOrStop($status, $id): void
    {
        $setmeal = Setmeal::query()->find($id);
        if (!$setmeal) {
            throw new \RuntimeException("套餐不存在");
        }
        $setmeal->status = $status;
        $setmeal->update_user = JwtHelper::getEmployee()->id;
        $setmeal->save();
    }
}